package com.wu.util;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;


/**
 * @author wangying
 * @version 1.0
 * @date 2023/12/21 14:40
 */
@Slf4j
public class JsonUtils {

    public static String toJSONString(Object obj) {
        if (null == obj) {
            return null;
        }
        try {
            return JSON.toJSONString(obj);
        } catch (Throwable e) {
            log.error("toJSONString {} failed, {}", obj, e);
        }
        return null;
    }

    public static <T> List<T> objToJavaObjectList(List<Object> objects, Class<T> tClass){
        if (CollectionUtil.isEmpty(objects)){
            return new ArrayList<>();
        }
        List<T> result=new ArrayList<>();
        try {
            for (Object obj:objects){
                if (ObjectUtils.isEmpty(obj)){
                    continue;
                }
                result.add(objToJavaObject(obj,tClass));
            }
        } catch (Throwable e) {
            log.error("objToJavaObjectList {} failed, {}", objects, e);
        }
        return result;
    }

    public static <T> T objToJavaObject(Object obj, Class<T> tClass) {
        return obj != null ? stringToJavaObject(toJSONString(obj), tClass) : null;
    }

    public static <T> T stringToJavaObject(String value, Class<T> tClass) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        try {
            return (T) JsonUtils.stringToJavaObjectList(value, tClass);
        } catch (Throwable e) {
            log.error("toJavaObject exception:{}, {}, {}", value, tClass, e);
        }
        return null;
    }

    public static <T> List<T> objToJavaObjectList(Object obj, Class<T> tClass) {
        return obj != null ? stringToJavaObjectList(toJSONString(obj), tClass) : Collections.emptyList();
    }

    public static <T> List<T> stringToJavaObjectList(String value, Class<T> tClass) {
        if (StringUtils.isNotBlank(value)) {
            try {
                return JSON.parseArray(value, tClass);
            } catch (Throwable e) {
                log.warn("toJavaObjectList exception {}, {}, {}", value, tClass, e);
            }
        }
        return new ArrayList<>();
    }

    public static Map<String, Object> toMap(String value) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        try {
            return JSON.parseObject(value, HashMap.class);
        } catch (Exception e) {
            log.error("toMap exception {}", value, e);
        }
        return null;
    }

}

